package com.li.online.service.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.li.online.service.base.exceptionhandler.GuliException;
import com.li.online.service.base.result.ResultCodeEnum;
import com.li.online.service.edu.entity.Subject;
import com.li.online.service.edu.entity.excel.SubjectExcelData;
import com.li.online.service.edu.listener.SubjectDataListener;
import com.li.online.service.edu.mapper.SubjectMapper;
import com.li.online.service.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author li
 * @since 2021-10-06
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    /**
     * new SubjectDataListener(baseMapper)使用带参构造
     * 将装配的SubjectMapper传入
     * @param file
     */
    @Override
    public void importSubject(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream())
                    .head(SubjectExcelData.class)
                    .registerReadListener(new SubjectDataListener(baseMapper))
                    .doReadAll();
        } catch (Exception e) {
            throw new GuliException(ResultCodeEnum.EXCEL_DATA_IMPORT_ERROR,e);
        }
    }

    @Override
    public List<Subject> getNestedSubject() {
        //查询所有课程分类
        List<Subject> subjects = baseMapper.selectList(null);
        //创建集合保存一级分类
        Map<String,Subject> pSubject = new HashMap<>();//键使用一级分类的id
        //挑出一级课程分类
        subjects.forEach(s->{
            if("0".equals(s.getParentId())){
                pSubject.put(s.getId(),s);
            }
        });
        //遍历二级分类，将他设置给自己的一级分类的子集合中
        subjects.forEach(s->{
            if(!"0".equals(s.getParentId())){
                Subject parentSubject = pSubject.get(s.getParentId());
                if(parentSubject!=null){
                    parentSubject.getChildren().add(s);
                }
            }
        });
        return new ArrayList<>(pSubject.values());
    }
}
